package com.devplatform.service.impl.article;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devplatform.mapper.CommentLikeMapper;
import com.devplatform.mapper.article.CommentsMapper;
import com.devplatform.pojo.CommentLike;
import com.devplatform.pojo.article.Comments;
import com.devplatform.pojo.dto.CommentPublishDto;
import com.devplatform.pojo.dto.CommentsDto;
import com.devplatform.pojo.vo.DataVo;
import com.devplatform.service.article.CommentsService;
import com.devplatform.service.points.PointsDetailService;
import com.devplatform.util.MessageUtil;
import com.devplatform.util.UserContextHolder;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author Jnks03
 * @description 针对表【comments】的数据库操作Service实现
 * @createDate 2025-09-29 16:27:19
 */
@Log4j2
@Service
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, Comments>
        implements CommentsService {
    @Autowired
    private CommentsMapper commentsMapper;
    @Autowired
    private PointsDetailService pointsDetailService;
    @Autowired
    private CommentLikeMapper commentLikeMapper;
    @Autowired
    private MessageUtil messageUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DataVo publish(CommentPublishDto dto) {
        Long userId = UserContextHolder.getUserId();// 获取当前登录用户ID
        log.info("userId:{}", userId);
        Comments comment = new Comments();
        comment.setArticleId(dto.getArticleId());
        comment.setUserId(userId);
        comment.setCommentContent(dto.getContent());
        comment.setLikeCount(0);
        comment.setReportCount(0);
        comment.setIsDeleted(0); // 默认为未删除
        commentsMapper.insert(comment);
        log.info("{}", comment);
        try {
            pointsDetailService.ArticlePoints(userId, "ARTICLE_REPLY");
        } catch (RuntimeException e) {
            // 积分发放失败不影响评论发布
            log.warn("用户{}回复评论积分发放失败：{}");
        }

        return DataVo.ok();
    }

    @Override
    public DataVo getCommentList(IPage<CommentsDto> commentsDtoIPage, Long articleId) {
        IPage<CommentsDto> commentDtoPage = commentsMapper.selectCommentDtoPage(commentsDtoIPage, articleId);
        return DataVo.ok(commentDtoPage);
    }

    @Override
    public DataVo delete(Integer commentId) {
        Long userId = UserContextHolder.getUserId();
        Comments comment = commentsMapper.selectById(commentId);
        // 校验：评论存在 + 未删除 + 是自己的评论
        if (comment == null || comment.getIsDeleted() == 1) {
            throw new RuntimeException("评论不存在或已删除");
        }
        if (!comment.getUserId().equals(userId)) {
            throw new RuntimeException("无权删除他人评论");
        }
        // 逻辑删除（MyBatis-Plus自动更新 is_deleted=1）
        commentsMapper.deleteById(commentId);
        return DataVo.ok();
    }

    @Override
    public DataVo like(CommentLike commentLike) {
        Long userId = commentLike.getUserId();
        Long commentId = commentLike.getCommentId();
        log.info(commentId);
        // 1. 检查用户是否已点赞（查询评论点赞关系）
        LambdaQueryWrapper<CommentLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommentLike::getUserId, userId)
                .eq(CommentLike::getCommentId, commentId);
        CommentLike hasLiked = commentLikeMapper.selectOne(queryWrapper);

        if (hasLiked != null) {
            commentLikeMapper.deleteById(hasLiked.getId());
            commentLikeMapper.decrementLikeCount(commentId);
            return DataVo.ok("取消点赞成功");
        } else {
            // 3. 未点赞 → 新增点赞（添加关系+增加点赞数）
            commentLike.setCreateTime(LocalDateTime.now());
            commentLikeMapper.insert(commentLike);
            commentLikeMapper.incrementLikeCount(commentId);

            return DataVo.ok("点赞成功");
        }
    }

    @Override
    public DataVo<Boolean> checkLikeStatus(Long userId, Long commentId) {
        LambdaQueryWrapper<CommentLike> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CommentLike::getUserId, userId)
                .eq(CommentLike::getCommentId, commentId);
        int count = Math.toIntExact(commentLikeMapper.selectCount(queryWrapper));
        return DataVo.ok(count > 0);
    }
    @Override
    public DataVo report(Integer commentId) {
        Comments comment = commentsMapper.selectById(commentId);
        if (comment == null || comment.getIsDeleted() == 1) {
            throw new RuntimeException("评论不存在");
        }
        comment.setReportCount(comment.getReportCount() + 1);
        commentsMapper.updateById(comment);
        return DataVo.ok();
    }
}




